<template>
  <div>
    <el-form
      ref="form"
      :rules="rules"
      style="padding-top: 10px"
      :model="form"
      label-width="100px"
    >
      <div class="com-form-title">基础信息</div>
      <el-row>
        <el-col :span="8">
          <el-form-item label="入库编号" prop="psNumber">
            <el-input
              v-model="form.psNumber"
              readonly
              :disabled="disableForm"
              placeholder="自动生成"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="入库时间" prop="psTime">
            <el-date-picker
              v-model="form.psTime"
              style="width: 100%"
              type="date"
              :disabled="disableForm"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="仓库名称" prop="storehouseName">
            <el-input
              v-model="form.storehouseName"
              readonly
              :disabled="disableForm || optType !== 'add'"
              @click.native="optType === 'add' ? (showStoreModal = true) : null"
            >
              <i
                slot="suffix"
                class="el-input__icon el-icon-circle-plus-outline"
              />
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="期次" prop="period">
            <el-input v-model="form.period" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="材料合同编号" prop="mcNumber">
            <!-- <el-input v-model="form.mcNumber" :disabled="disableForm" /> -->
            <el-input
              v-model="form.mcNumber"
              readonly
              :disabled="disableForm || optType !== 'add'"
              @click.native="
                optType === 'add' ? (showAgreementModal = true) : null
              "
            >
              <i
                slot="suffix"
                class="el-input__icon el-icon-circle-plus-outline"
              />
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="材料合同名称" prop="mcName">
            <el-input v-model="form.mcName" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="送货人" prop="deliveryMan">
            <el-input v-model="form.deliveryMan" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="收料员" prop="collector">
            <el-input v-model="form.collector" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="8">
          <el-form-item label="供应商编号" prop="supplierNumber">
            <el-input v-model="form.supplierNumber" :disabled="disableForm" />
          </el-form-item>
        </el-col> -->
        <el-col :span="8">
          <el-form-item label="供应商名称" prop="supplierName">
            <el-input v-model="form.supplierName" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="金额" prop="amount">
            <el-input v-model="form.amount" :disabled="disableForm" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="描述" prop="description">
            <el-input v-model="form.description" :disabled="disableForm" />
          </el-form-item>
        </el-col>
      </el-row>

      <div style="padding-bottom: 10px">
        <el-button type="primary" :disabled="disableForm" @click="showTargetSetListModal = true">引入材料编码</el-button>
      </div>
      <com-table
        v-model="selectRow"
        highlight-current-row
        :data="targetList"
        :columns="columns"
        :no-page="true"
      >
        <template v-slot:number="{ row }">
          {{ row.number || row.code }}
        </template>
        <template v-slot:name="{ row }">
          <el-input v-model="row.name" :disabled="disableForm" />
        </template>
        <template v-slot:specification="{ row }">
          <el-input v-model="row.specification" :disabled="disableForm" />
        </template>
        <template v-slot:unit="{ row }">
          <el-input v-model="row.unit" :disabled="disableForm" />
        </template>
        <template v-slot:count="{ row }">
          <el-input v-model="row.count" :disabled="disableForm" @input="getSumPrice" />
        </template>
        <template v-slot:unitPrice="{ row }">
          <el-input v-model="row.unitPrice" :disabled="disableForm" @input="getSumPrice" />
        </template>
        <template v-slot:price="{ row }">
          <el-input v-model="row.price" :disabled="disableForm" />
        </template>

        <template v-slot:otherPrice="{ row }">
          <el-input v-model="row.otherPrice" :disabled="disableForm" @input="getSumPrice" />
        </template>
        <template v-slot:otherPriceDesc="{ row }">
          <el-select
            v-model="row.otherPriceDesc"
            :disabled="disableForm"
            style="width: 100%"
            placeholder="请选择"
          >
            <el-option
              v-for="item in otherPriceDescTypes"
              :key="item.name"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </template>
        <template v-slot:sumPrice="{ row }">
          <el-input v-model="row.sumPrice" :disabled="disableForm" />
        </template>
        <template v-slot:amount="{ row }">
          <el-input v-model="row.amount" :disabled="disableForm" />
        </template>
        <template v-slot:qualityInspectionNumber="{ row }">
          <el-input
            v-model="row.qualityInspectionNumber"
            :disabled="disableForm"
          />
        </template>
        <template v-slot:description="{ row }">
          <el-input v-model="row.description" :disabled="disableForm" />
        </template>
        <template v-slot:createTime="{ row }">
          {{ dateFormat(row.createTime) }}
        </template>
        <template v-slot:options="{ row }">
          <el-button
            :disabled="disableForm"
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="deleteTarget(row)"
          >删除</el-button>
        </template>
      </com-table>
      <el-button
        style="margin-top: 10px"
        type="primary"
        @click="showFileModal = true"
      >附件资料({{ fileList.length }})</el-button>
      <file-uploader
        v-model="fileList"
        :show-modal.sync="showFileModal"
        :disabled="disableForm"
        :can-download="optType === 'detail'"
      />
    </el-form>
    <tree-modal
      title="材料编码选择(多选)"
      :show-modal.sync="showTargetSetListModal"
      :columns="columns"
      :api-obj="{ tree: getMaterialDirectoryTree, list: getMaterialDetailList }"
      @getSelectedRows="getSelectedRows"
    />
  </div>
</template>

<script>
import {
  addProjectPurchaseStorehouseInfo,
  updateProjectPurchaseStorehouseInfo,
  getProjectPurchaseStorehouseInfoDetail
} from '@/api/materialManage'
import { getAreaList } from '@/api/common'
import { workflowStatus, otherPriceDescTypes } from '@/utils/dicData'
import fileUploader from '@/components/FileUploader'
import TreeModal from '@/components/TreeModal'
import {
  getMaterialDirectoryTree,
  getMaterialDetailList
} from '@/api/basicCode'

export default {
  name: 'AddProjectPurchaseStorehouseInfo',
  components: {
    fileUploader,
    TreeModal
  },
  props: {
    showModal: {
      type: Boolean,
      default: false
    },
    optType: {
      type: String,
      default: 'add'
    },
    dir: {
      type: Object,
      default() {
        return {}
      }
    },
    data: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      getMaterialDirectoryTree,
      getMaterialDetailList,
      showAgreementModal: false,
      showStoreModal: false,
      showFileModal: false,
      otherPriceDescTypes,
      selectRow: null,
      targetList: [],
      workflowStatus,

      addType: '', // same   under
      visible: false,
      showAdd: false,
      selectedNode: null,
      form: {
        psNumber: '',
        psTime: '',
        storehouseName: '',
        period: '',
        mcNumber: '',
        mcName: '',
        deliveryMan: '',
        collector: '',
        supplierNumber: '',
        supplierName: '',
        amount: '',
        description: '',
        addWorkflowId: '',
        status: '',
        founderName: '',
        createTime: '',
        founderUnit: ''
      },
      columns: [
        {
          label: '材料编号',
          prop: 'number',
          slot: 'number'
        },
        {
          label: '材料名称',
          prop: 'name'
        },
        {
          label: '规格',
          prop: 'specification'
        },
        {
          label: '单位',
          prop: 'unit'
        },
        {
          label: '单价',
          prop: 'unitPrice',
          slot: 'unitPrice',
          width: '150'
        },
        {
          label: '数量',
          prop: 'count',
          slot: 'count',
          width: '150'
        },
        {
          label: '其他费用',
          slot: 'otherPrice',
          width: '150'
        },
        {
          label: '其他费用说明',
          slot: 'otherPriceDesc',
          width: '140'
        },
        {
          label: '总价',
          slot: 'sumPrice',
          width: '120'
        },
        {
          label: '质检批号',
          slot: 'qualityInspectionNumber'
        },
        {
          label: '描述',
          slot: 'description'
        },
        // {
        //   label: '编制时间',
        //   prop: 'createTime',
        //   slot: 'createTime'
        // },
        {
          fixed: 'right',
          label: '操作',
          width: '140',
          prop: 'options',
          slot: 'options'
        }
      ],
      showTargetSetListModal: false,
      fileList: [],
      rules: {
        name: [{ required: true, message: '单位名称', trigger: 'change' }],
        unifiedSocialCreditCode: [
          { required: true, message: '统一社会信用代码', trigger: 'change' }
        ]
      },
      provinceData: [],
      cityData: []
    }
  },
  computed: {
    disableForm() {
      return this.optType === 'detail'
    },
    show: {
      get() {
        return this.showModal
      },
      set(val) {
        this.$emit('update:showModal', val)
      }
    }
  },
  watch: {
    data: {
      handler(newData, oldData) {
        if (newData.id) {
          this.getDocDetail(newData.businessId)
        }
      },
      deep: true,
      immediate: true
    }
  },
  mounted() {
    this.getRegionData()
  },
  methods: {
    total() {
      let sum = 0
      this.targetList.forEach((element) => {
        sum += element.sumPrice * 1
      })

      this.form.amount = sum

      this.$forceUpdate()
    },
    sum() {
      this.selectRow.sumPrice =
        this.selectRow.unitPrice * this.selectRow.count +
        this.selectRow.otherPrice * 1
      this.total()
      this.$forceUpdate()
    },
    getSelectedData(type, data) {
      if (type === 'store') {
        this.form.storehouseName = data.name
      }
      if (type === 'agreement') {
        const { name, number, employeeName, employeeNumber, contractAmount } =
          data
        this.form.mcName = name
        this.form.mcNumber = number
        this.form.amount = contractAmount
        this.form.supplierNumber = employeeNumber
        this.form.supplierName = employeeName
      }
    },
    deleteTarget(obj) {
      // this.targetList.map((item, m) => {
      //   if (item.code === obj.code) {
      //     this.targetList.splice(m, 1)
      //   }
      // })
      this.$confirm('确定要删除该材料数据吗, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          const index = this.targetList.indexOf(obj)
          if (index > -1) {
            this.targetList.splice(index, 1)
          }
        })
        .catch(() => {})
    },
    getSelectedRows(data) {
      this.targetList = this.targetList.concat(
        data.map((item) => {
          return {
            ...item
          }
        })
      )
    },
    provinceChange(e) {
      const selectedData = this.provinceData.filter((val) => val.name === e)[0]
      if (selectedData) {
        this.form.city = ''
        const params = {
          parentCode: selectedData.code,
          areaType: 2
        }
        getAreaList(params).then((res) => {
          this.cityData = res.data || []
        })
      }
    },
    getDocDetail(id) {
      getProjectPurchaseStorehouseInfoDetail({
        projectPurchaseStorehouseInfoId: id
      }).then((res) => {
        const { lstAttachment, projectPurchaseStorehouseInfo, lstProjectPurchaseStorehouseDetail } = res.data || {}
        Object.keys(this.form).forEach(key => {
          const source = projectPurchaseStorehouseInfo[key]
          if (typeof source === 'boolean') {
            this.form[key] = source ? 1 : 0
          } else {
            this.form[key] = source
          }
        })
        if (lstAttachment && lstAttachment.length > 0) {
          this.fileList = lstAttachment
        }
        if (
          lstProjectPurchaseStorehouseDetail &&
          lstProjectPurchaseStorehouseDetail.length > 0
        ) {
          this.targetList = lstProjectPurchaseStorehouseDetail
        }
      })
    },
    getRegionData() {
      getAreaList({ areaType: '1' }).then((res) => {
        this.provinceData = res.data || []
      })
    },
    deleteDetail() {},
    saveDoc() {
      if (this.optType === 'detai') {
        this.show = false
        return
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.targetList.map((item) => {
            item.id = ''
          })
          const params = {
            projectPurchaseStorehouseInfo: {
              ...this.form,
              ...(this.optType === 'edit'
                ? {
                  id: this.data.id
                }
                : {})
            },
            lstAttachment: this.fileList,
            lstProjectPurchaseStorehouseDetail: this.targetList.map((item) => {
              return {
                ...item,
                ...(this.optType === 'edit'
                  ? {
                    projectPurchaseStorehouseInfoId: this.data.id
                  }
                  : {})
              }
            })
          }
          const fn =
            this.optType === 'add'
              ? addProjectPurchaseStorehouseInfo
              : updateProjectPurchaseStorehouseInfo
          fn(params).then((res) => {
            if (res.code === '0001') {
              this.$message({
                type: 'success',
                message: '保存成功!'
              })
              this.show = false
              this.$emit('freshList')
              this.$refs.form.resetFields()
            } else {
              this.$message({
                type: 'error',
                message: res.msg
              })
            }
          })
        }
      })
    },
    getSumPrice() {
      this.targetList.forEach((item, index) => {
        let sum = 0
        let unitPrice = 0
        let count = 0
        let otherPrice = 0
        if (item.unitPrice) {
          unitPrice = item.unitPrice
        }
        if (item.count) {
          count = item.count
        }
        if (item.otherPrice) {
          otherPrice = item.otherPrice
        }
        sum = Number.parseFloat(count) * Number.parseFloat(unitPrice) + Number.parseFloat(otherPrice)
        item.sumPrice = sum.toFixed(2)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.com-form-title{
  font-size: 14px;
  font-weight: bold;
  line-height: 35px;
  color: #409EFF;
  border-bottom: 1px solid #dedede;
  margin-bottom: 6px;
}

::v-deep .el-form-item__label{
  color: #000;
}
::v-deep .el-input.is-disabled .el-input__inner{
  color: #000;
}
::v-deep .el-input.is-disabled .el-input__inner{
  color: #000;

}
</style>
